var myUploadComplete,myFilesAdded;

//创建一个闭包  
(function($) {  
	
	
	$.fn.setDisable = function(trueorfalse) {
		var id = $(this).attr("id");		
		$("#" + id + "Show").attr("disabled",trueorfalse);
		if (trueorfalse == true) {
			$("#" + id + "Reset").hide();			
		} else {
			$("#" + id + "Reset").show();			
		}
	};
	
	$.fn.getShowText = function() {
		var id = $(this).attr("id");		
		return $("#" + id + "Show").val();
	};
	
	$.fn.reset = function() {
	  var resetId = $(this).attr("id") + "Reset";
	  $("#" + resetId).click();
	};	
	
	$.fn.setShow = function(showName) {
		var id = $(this).attr("id");		
		$("#" + id + "Show").val(showName);
	};	
	Orginput = {
			defaluts: {
				isCheckOrg:'0',    //是否需要展示右键菜单，0-不展示，1-展示
			  	checkType:'org',   //机构树类型：org-展示机构；dept-展示机构、部门；user-展示机构、部门、人员
			  	messageType:'org', //节点类型，传输到后台查询的节点类型，默认为org-机构，另外有dept-部门
			  	noSuper:'',        //如果为管理类实体机构，是否需要将权限上升到对应虚拟机构，默认上升，如果不用上升，则此值设置为"noSuper"
				reset: '1',
				clickType:'',
			    defaultOrgId: '',  //默认机构号
			    defaultOrgName: '',//默认机构名称
			    debug: false,
			    readonly: false,
			    isCheckBox:false, //是否需要复选
			    forReport:false, //是查询报表统计机构数还是经营管理机构数，默认是经营管理机构数
			    queryRootOrgId:'',//查询机构数时的指定子机构数跟节点，默认为整个机构树的根节点
			    isNotCheckMessageType:false, //选择时，是否验证节点属性
			    mapper:{
			    	 mapperId:'',
			    	 paramsJson:''
			    },
			    beforeSelect: function() { return true; },
			    onChange : function() {},
			    afterSelect: function() { return true; }
			},
			init:   function(obj,options) {
					var opts = $.extend({}, $.fn.orgTreeSelect.defaults, options);  
					_init(obj, opts);
				}
	  };  
	// 机构树插件  
	  $.fn.orgTreeSelect = function(options) {  
	    // build main options before element iteration  
	    var opts = $.extend({}, $.fn.orgTreeSelect.defaults, options);  
	    // iterate and reformat each matched element  
	    return this.each(function() {
	    	    var $this = $(this);
		    	_init($this, opts);
		});
	  };
	  $.fn.orgTreeSelect.defaults = {
			  	checkType:'org',   //机构树类型：org-展示机构；dept-展示机构、部门；user-展示机构、部门、人员
			  	//messageType:'org', //节点类型，传输到后台查询的节点类型，默认为org-机构，另外有dept-部门
			  	//noSuper:'',        //如果为管理类实体机构，是否需要将权限上升到对应虚拟机构，默认上升，如果不用上升，则此值设置为"noSuper"
				//reset: '1',  
			  	clickType:'',
			    defaultOrgId: '',  //默认机构号
			    defaultOrgName: '',//默认机构名称
			    debug: false,
			    readonly: false,
			    //isCheckBox:false, //是否需要复选
			    queryRootOrgId:'',//查询机构数时的指定子机构数跟节点，默认为整个机构树的根节点
			    mapper:{
			    	 mapperId:'',
			    	 paramsJson:''
			    },
			    beforeSelect: function() { return true; },
			    onChange : function() {}
	  };
	  
	// 用户选择插件  
	  $.fn.userinput = function(options) {
		 // debugger;
	    // build main options before element iteration  
	    var opts = $.extend({}, $.fn.userinput.defaults, options); 
	  	if (opts.debug == true) {
			//debugger;
		}
	  	
	    $("#common_select_user_container").remove();
		$("BODY").append('<div id="common_select_user_container"></div>');
	    
	    // iterate and reformat each matched element  
	    return this.each(function() {    
	    	//debugger;
	    	var displayNameId = $(this).attr("id") + "Show";
	    	if (opts.displayNameId != '') {
	    		displayNameId = opts.displayNameId;
	    	}
	    	var defaultUserCode = opts.defaultUserCode;
	    	var defaultUserName = opts.defaultUserName; 
	    	var $this = $(this);
	    	if($("#"+displayNameId)){
	    		$("#"+displayNameId).remove();
	    	}
	    	$(this).hide();
	    	$(this).val(defaultUserCode);
	    	if(opts.readonly==true){
	    		$(this).after("<input id='" + displayNameId + "' class='col-xs-10' type='text'  value='" + defaultUserName + "' readonly />");
	    	}else{
	    		$(this).after("<input id='" + displayNameId + "' class='col-xs-10' type='text'  value='" + defaultUserName + "' />");
	    	}
	    	var resetUserId = $(this).attr("id") + "Reset";   
	    	if($("#"+resetUserId)){
	     		$("#"+resetUserId).remove();
	     	}
	    	$("#"+displayNameId).after('<a id="' + resetUserId + '" class="ui-icon ui-icon-close" style="float:left;margin-left:.5em;" href="#"></a>');
	     	$("#" + resetUserId).click(function() {
	     		$(this).val("");
	     		$("#"+displayNameId).val("");
	     	}); 
	    	if (opts.readonly == false) {
	    		if($("#"+resetUserId)){
		    		$("#"+resetUserId).remove();
		    	}
	        	$("#" + displayNameId).after('<a id="' + resetUserId + '" class="ui-icon ui-icon-close" style="float:left;margin-left:.5em;" href="#"></a>');
	        	if (opts.reset != '1') {
	        		$("#" + resetUserId).hide();
	        	}    	
	    	}
	        	
	        	$("#" + displayNameId).click(function() {
	        		if (opts.beforeSelect() == false) {
	        			return;
	        		}
	            	$("#common_select_user_container").dialog({hide:true,autoOpen:false,width:900,height:580,modal:true,bgiframe:true,title:"用户选择",
	            		buttons: 
	            		[
							{
								id: "btnSave",
								html: "<i class='ace-icon fa fa-floppy-o bigger-110'></i>&nbsp; 确认",
								"class" : "btn btn-success btn-minier",
								click: function() {
									//debugger;
									if($("#retValue").val()==""){
		            					alert("请选择用户！");
		            					return;
		            				}
		            				var arr=eval('('+$("#retValue").val()+')');
		            				if (arr.userId != $this.val()) {
		            					$this.val(arr.userName);
		            					$("#" + displayNameId).val(arr.userName+"("+arr.userId+")");            					
		            					opts.onChange(arr);
		            				}
		        					
		            				$(this).dialog("close");
								}
							},
							{
								id: "btnClose",
								html: "<i class='ace-icon fa fa-undo bigger-110'></i>&nbsp; 关闭",
								"class" : "btn btn-warning btn-minier",
								click: function() {
									$(this).dialog("close");
								}
							}
	            		],
	            		close: function(event, ui) {
	            			$("#common_select_user_container").dialog("destroy");
	            			$("#common_select_user_container").empty();
	            		}
	            	});	   	
	            	var belongArea = opts.belongArea;
	            	var belongDept = opts.belongDept;
	            	var userRole = opts.userRole;
	            	if (opts.belongAreaId != '') {
	            		belongArea = $("#"+opts.belongAreaId).val();
	            	}
	            	if (opts.belongDeptId != '') {
	            		belongDept = $("#"+opts.belongDeptId).val();
	            	}
	            	if (opts.userRoleId != '') {
	            		userRole = $("#"+opts.userRoleId).val();
	            	} 
	            	var params = { "_belongArea" : belongArea, "_belongDept" : belongDept, "_userRole" :userRole };
	            	$("#common_select_user_container").load(base + "/component/queryUser.do", $.param(params));
	            	$("#common_select_user_container").dialog("open");          	
	        	});
	        	
	         	$("#" + resetUserId).click(function() {
	        	  	$this.val("");
	        	  	$("#" + displayNameId).val("");
	        	  	opts.onChange();
	        	});    		
	    });
	  };  
	  
	  // 用户插件的defaults  
	  $.fn.userinput.defaults = {
	    displayNameId: '',  
	    defaultUserCode: '',
	    defaultUserName: '',
		reset: '1',  
	    debug: false,
	    belongArea: '',
	    belongDept: '',
	    userRole: '',
	    belongAreaId: '',    //关联的机构选择控件id
	    belongDeptId: '',    //关联的部门选择控件id
	    userRoleId: '',      //关联的角色选择控件id
	    readonly: true,   
	    onChange: function(user) {},
	    beforeSelect: function() { return true; }
	  }; 
	  
	  
	  // 提交流程审批插件  
	  $.fn.submitflow = function(options) {
	    // build main options before element iteration  
	    var opts = $.extend({}, $.fn.submitflow.defaults, options); 
	  	if (opts.debug == true) {
			//debugger;
		}
	  	
	    $("#common_flow_select_container").remove();
		$("BODY").append('<div id="common_flow_select_container"></div>');
		var params = {
				"partBeanName":'', 
				"flowPart":'', 
				"flowSeq":opts.flowSeq, 
				"reSumit":opts.reSumit, 
				"relativeFlowId":opts.relativeFlowId, 
				"flowId":opts.flowId, 
				"flowType":opts.flowType, 
				"flowVerson":1, 
				"busiId":opts.busiId, 
				"busiApplyType":opts.busiType, 
				"isMainFlow":opts.isMainFlow, 
				"applyUserId":opts.applyUserId, 
				"applyUserOrg":opts.applyUserOrg, 
				"applyUserDept":opts.applyUserDept, 
				"flowStatus":'0', 
				"applyTime":opts.applyTime 
			};	
		
		//流程选择
		$("#common_flow_select_container").dialog({
			hide:true,
			autoOpen: false,
			width: 700,
			height: 250,
			modal: true,
			title:"流程发送",
			buttons: {
				"确认": function() {
					if ($("#nextPart").val() == "") {
						$("#nextPart").addClass( "ui-state-error" );
						updateTips("请选择下一处理环节！");
						return;				
					}
				
					if ($("#nextUserName").val() == "") {
						$("#nextUserName").addClass( "ui-state-error" );
						updateTips("请选择下一处理人！");
						return;
					}
					
					$("#nextDept").attr("disabled",false);
					$("#nextRole").attr("disabled",false);	
					$("#nextPart").attr("disabled",false);				
					$.ajax({
						url : base + "/flow/flow!submit.action",
						async : false,
						data : $.param(params) + "&" + $("#nextForm").serialize() + '&dealConfig={"smsNotify":"'+ $("#smsNotify").val()+'"}',
						type : "POST",
						dataType : "json",
						success : function(data, textStatus) {
							if (data[0] == "ok") {
								opts.afterSubmit(data[0], data[1]);
							} else {
								alert(data[1]);
							}						
						}
					});
					$(this).dialog("close");				
				},
				"取消": function() {
					$(this).dialog( "close" );
				}			
			},
			close: function(event, ui) {
    			$("#common_flow_select_container").html("");
			}		
		});		
	    
	    // iterate and reformat each matched element  
	    return this.each(function() {
	    	$(this).click(function() {
	    		if (opts.beforeSubmit() == false) {
	    			return;
	    		}
		
				$.ajax({
					url : base + "/flow/getFlowDefine.do",
					async : true,
					data : $.param(params),
					type : "POST",
					dataType : "json",
					success : function(data, textStatus) {
						if (data[0] != "ok") {
							alert("流程配置错误！");
							return;
						}
						params = $.extend({}, params, {"flowVerson":data[1], "flowPart":data[2], "partBeanName":data[3]}); 
						if (opts.busiIdObjectId != '') {
							params = $.extend({}, params, {"busiId": $("#" + opts.busiIdObjectId).val()}); 
						}
						if (opts.reSumitObjectId != '') {
							params = $.extend({}, params, {"reSumit": $("#" + opts.reSumitObjectId).val()}); 
						}
						if (opts.flowTypeId != '') {
							params = $.extend({}, params, { "flowType": $("#" + opts.flowTypeId).val() });
						}						
						if (opts.busiTypeId != '') {
							params = $.extend({}, params, { "busiApplyType": $("#" + opts.busiTypeId).val() });							
						}
						
						if(opts.summary !=''){
							params = $.extend({}, params, { "summary": $("#"+opts.summary).val() });
						}
						
						$("#common_flow_select_container").load(base + "/flow/next.do", $.param(params));
						$("#common_flow_select_container").dialog("open");
					}
				});
	    	});    	
	    });
	  };  
	  
	  // 流程提交插件的defaults  
	  $.fn.submitflow.defaults = {
		busiId: '',  
		busiIdObjectId: '',
		busiType: '',  
		busiTypeId: '', 
		flowType: '',  
		flowTypeId: '',  
		isMainFlow: '1',
		applyUserId: '',
		applyUserOrg: '',
		applyUserDept: '',
		reSumit: '0',
		reSumitObjectId: '',
		flowId: '',
		flowSeq: '1',
		relativeFlowId: '',
		summary:'',
	    debug: false,
	    beforeSubmit: function() { return true; },
	    afterSubmit: function() {}
	  }; 
	  
	  function updateTips(t) {
		var tips = $("#selectFlowValidate");
		tips.html('<span class="ui-icon ui-icon-alert" style="float: left; margin-right: .3em;"></span>' + t).addClass( "ui-state-error" );
	  } 
	  
	  
	//根据机构返回部门列表插件
	  $.fn.deptSelect = function(options){
		  //debugger;
		  var opts = $.extend({}, $.fn.deptSelect.defaults, options); 
		  	if (opts.debug == true) {
				//debugger;
			}
		  	$("#common_depttree_container").remove();
		 	$("BODY").append('<div id="common_depttree_container"></div>');
		    return this.each(function() {
		    	var obj = $(this);
		    	var defaultDeptId = opts.defaultDeptId;
		    	var showDeptId = obj.attr("id") + "Show";
		    	var defaultDeptName = opts.defaultDeptName; 
		    	if(defaultDeptId != "") {
		    		obj.val(defaultDeptId);
		    	}
		    	if($("#"+showDeptId)){
		    		$("#"+showDeptId).remove();
		    	}
		    	//获得obj的标签名、属性、样式并克隆一个一模一样的标签，id加个Show后缀
		     	var id = obj.attr("id");
		     	obj.wrap("<div></div");
		     	var objhtml = obj.parent().html();
		     	obj.attr("id", showDeptId);
		     	//obj.after("<input id='" + showOrgId + "' style='float:left' type='text' value='"+defaultOrgName+"'/>");
		     	obj.after(objhtml);
		     	var newobj = $("#"+id);
		     	newobj.attr("id", showDeptId);
		     	obj.attr("id", id);
		     	newobj.attr("value", defaultDeptName);
		     	newobj.attr("name","");
		     	newobj.attr("class","col-xs-10 col-sm-8");
		     	newobj.attr("readonly", true);
		     	newobj.show();
		     	obj.hide();
		     	var resetDeptId = id +"Reset";
		     	if($("#"+resetDeptId)){
		     		$("#"+resetDeptId).remove();
		     	}
		     	newobj.css("float","left");
		     	newobj.after('<a id="' + resetDeptId + '" class="ui-icon ui-icon-close" style="float:left;margin-left:.5em;" href="#"></a>');
		     	$("#" + resetDeptId).click(function() {
		      		obj.val("");
		      		newobj.val("");
		     	}); 
		    	$("#"+showDeptId).click(function(){
		    		if (!opts.beforeSelect()) {
			 			return;
			 		}
		    		if(opts.afterSelect != undefined || opts.afterSelect !=null){
						opts.afterSelect();
				}
		    		if(!opts.isCheckBox) {
		        		$("#common_depttree_container").dialog({hide:true,autoOpen: false,width: 400,height:500, modal: true,bgiframe: true,resizable: false,position: {
		    				my: "center",
		    				at: "center",
		    				of: window,
		    				within: $("body")
		    				},title:"部门选择",
		        			close: function(event, ui) {
		        				if($("#returnData").val() != "") {
		        					var arr=eval("("+$("#returnData").val()+")");
		        					if(arr != null) {
			        					obj.val(arr.deptId);
			        					$("#" + showDeptId).val(arr.deptName);
		        					}
		        					opts.afterSelect(arr.deptId, arr.deptName);
		        				}
		            			$("#common_depttree_container").dialog("destroy");
		            			$("#common_depttree_container").empty();
		        			}			
		        		});
		 		} else{
		 			 $("#common_depttree_container").dialog({hide:true,autoOpen:false,width:700,height:480,top: 259, left:750,modal:true,bgiframe:true,title:"部门选择",
		    			 buttons: {
								"确认": function() {
									var checkedNodes = zTreeSelect.getCheckedNodes(true);
									$("#returnData").data("treeNode", checkedNodes);
									$("#common_depttree_container").dialog("close");
								},
								"关闭": function() {
									$("#common_depttree_container").dialog("close");
								}
							},
		        			close: function(event, ui) {
		        				var checkedNodes = $("#returnData").data("treeNode");
		        				var deptIds = "",deptNames = "";
								if(checkedNodes) {
									for(var i = 0; i < checkedNodes.length;i++) {
										deptIds = deptIds + checkedNodes[i].id + ",";
										deptNames = deptNames + checkedNodes[i].name + ",";
									}
									alert();
									obj.val(deptIds.substr(0,deptIds.length - 1));
									$("#" + showDeptId).val(deptNames.substr(0,deptNames.length - 1));
									opts.afterSelect(deptIds, deptNames);
								}
		            			$("#common_depttree_container").dialog("destroy");
		            			$("#common_depttree_container").empty();
		        			}
		            	});
		 		}
		    		
	            	var params = {"orgId" : opts.orgId,"clickType":opts.clickType};
	            	var jsonParam=JSON.stringify(params);
	            	$("#common_depttree_container").load(base+"/org/deptSelectTree", {"params":jsonParam});
	            	$("#common_depttree_container").dialog("open");
		    	});
			   
		    });
	  };
	  $.fn.deptSelect.defaults = {
			  orgId: '',
			  defaultDeptId:'',
			  defaultDeptName:'',
			  beforeSelect:function(){return true;},
			  afterSelect:function(deptIds, deptNames){return true;},
			  isCheckBox:false,
			  debug:'false'
	  };
	  
	  $.fn.myfileupload = function(options){
			 var opts = $.extend({}, $.fn.myfileupload.defaults, options); 	    
			 if (opts.debug == true) {
				//debugger;
			 }
			 if(opts.url == ''){
			 	if(opts.type=='file'){
			 		opts.url = base+"/file/upload.do";
			 		if(opts.filters ==''){
			 			opts.filters = "*";
			 		}
			  	}else if(opts.type=='image'){
			  		opts.url=base+"/file/upload.do";	
			  		opts.filters = "jpg,jpeg";
			  	}
			  }
			 //附上参数
			 var params = {"busiId":opts.busiId, "orgId":opts.orgId, "thumbWidth":opts.thumb_width, "thumbHeight":opts.thumb_height};
	         return this.each(function() {	 
			    	$(this).click(function(){
			    		//debugger;
			    		$("BODY").append('<div id="fileUploadPage"></div>');
			    		//dialog start
			    		$('#fileUploadPage').dialog({
			    			hide:true,
			    			autoOpen:false,
			    			width: 800,
			    			height:430,
			    			modal:true,
			    			title: "文件上传",
			    			title_html: true,			
			    			buttons: [
			    				{
			    					id: "btnPClose",
			    					html: "<i class='ace-icon fa fa-times bigger-110'></i>&nbsp; 关闭",
			    					"class" : "btn btn-minier",
			    					click: function() {
			    						$(this).dialog("close");
			    						$(this).empty();
			    					}
			    				}	
			    			]
			    			
			    		});
			    		var id = $(this).attr("id");
			    		$("#"+id+"uploader").remove();
					 	//$("#fileUploadPage").append('<div id="'+id+'uploader" ><div  class="pluploadwrap"></div><div class="pluploadminipan"><div id="uploader"></div><div><input type="button" id="closebtn" value="关闭"></div></div><div>');
			    		$("#fileUploadPage").load(base+"/demo/uploadPage.do",function(){
			    		$("#dropzone").pluploadQueue({  
							url : opts.url, 	 
						  	file_data_name:"file", 
						  	filters : {     
									mime_types: [{title: "Select files", extensions :opts.filters}]        
							  	},   
							multipart_params:params,
						    unique_names:false,//文件名是否唯一
							multiple_queues:opts.multi_selection,//是否可以多次上传
							dragdrop: true,  
							chunk_size: opts.chunk_size, 	
		  	                multi_selection: opts.multi_selection,//是否可以一次选择多个文件 true
							resize: {width: opts.resize_width, height:opts.resize_height ,quality:opts.resize_quality,crop: true}, 
		  	                runtimes : 'html5,flash,silverlight,html4', 
						  	runtimes : 'html5,flash,silverlight,html4', 
						  	flash_swf_url : base+'/assets/js/plupload/Moxie.swf',         
						  	silverlight_xap_url : base+'/assets/js/plupload/Moxie.xap',
							init: {//files为本次选择的文件列表；up对象中的files属性表示上传队列中的总文件列表(不包括本次选择的文件) 
								filesAdded: opts.myFilesAdded,//文件添加时  			
								uploadComplete:opts.myUploadComplete,//所有文件上传成功时
								error:opts.error,
								fileUploaded:opts.myFileUploaded
							}
						 }); 
			    	 }); 
			    		//打开文件上传之前判断
			    		 if(undefined!=opts.checkBefore){
							 if(!checkBefore()){
								 return;
							 }
						 }
			    	$("#fileUploadPage").dialog("open");
			    	//debugger;
			    		//根据不同浏览器类型用不同方法获取浏览器窗口大小 目前支持ie和firefox 其他浏览器使用默认大小
					    var browseros = getOs();
					    var clientWidth = 800;
					    if(browseros == 'MSIE') {
					    	clientWidth = document.documentElement.clientWidth;
					    	
					     }else if(browseros=='Firefox') {
					     	clientWidth = document.body.clientWidth;
					     }
					    if(browseros == 'MSIE'){
					    	$(".pluploadminipan").css({width:clientWidth * 0.5});
					    }else{
					    	$(".pluploadminipan").css({width:clientWidth});
					    }
			    	
				    //禁用滚动条
			      /* $(document.body).css({
			         "overflow-x":"hidden",
			         "overflow-y":"hidden"
			       });
			       document.body.scroll = "no";
			    	$("#btnPClose").click(function(){
			    		$("#"+id+"uploader").remove();
			    		 //启用滚动条
				        $(document.body).css({
				          "overflow-x":"auto",
				          "overflow-y":"auto"
				        });
				        document.body.scroll = "yes";
			    	 });*/
			      }); 
	         }); 
		 };
		 
		 $.fn.myfileupload.defaults = {
				  url:'',//自定义url 如果为空则用默认的url处理
				  busiId:'', //作为文件的挂靠业务id 必输
				  orgId:'', //作为区分文件的维度，非必输
				  type:'file',
				  filters: "",  //上传文件类型,格式 "txt,zip,img"等 
				  chunk_size: '1G', //文件分割成多大的子文件  默认为1G 即分割
				  max_file_size: "1GB",//单个文件的最大文件大小			
				  multi_selection: true,//是否可以一次选择多个文件 默认可以					
				  debug: false,
				  myUploadComplete:function(up,files){/*alert("所有文件上传成功");*/},//所有文件上传成功时 
				  myFilesAdded: function(up, files){},//文件添加时 
				  myFileUploaded:function(up, file, res){},//该事件可以从后台传回json数据格式,存在res.response对象中（字符串），是从后台返回数据的唯一方法，可以在url的action中自定义；
				  error:function(up, err){}
		 };
		 
		 
		 
		 
		 
		 
		 $.fn.hiwanFileUpload = function(options){
			 var opts = $.extend({}, $.fn.hiwanFileUpload.defaults, options); 
			 //附上参数
			 var params = {"busiId":opts.busiId, "orgId":opts.orgId};
	         return this.each(function() {	 
		    	$(this).click(function(){
		    		//debugger;
		    		$("BODY").append('<div id="fileUploadPage"></div>');
		    		
		    		//dialog start
		    		$('#fileUploadPage').dialog({
		    			hide:true,
		    			autoOpen:false,
		    			width: 750,
		    			height:400,
		    			modal:true,
		    			title: "文件上传",
		    			title_html: true,			
		    			buttons: [
		    				{
		    					id: "btnPSave",
		    					html: "<i class='ace-icon fa fa-floppy-o bigger-110'></i>&nbsp; 确定",
		    					"class" : "btn btn-success btn-minier",
		    					click: function() {
		    						$("#fileUploadPage").dialog("close");
		    					}
		    				},
		    				{
		    					id: "btnPClose",
		    					html: "<i class='ace-icon fa fa-undo bigger-110'></i>&nbsp; 取消",
		    					"class" : "btn btn-warning btn-minier",
		    					click: function() {
		    						$("#fileUploadPage").dialog("close");
		    					}
		    				}												
		    			]
		    		});
		    		//dialog end
		    		$("#fileUploadPage").load(base+"/demo/uploadPage.do",function(){
		    			
		    			//文件上传插件 start
			    		$("#dropzone").dropzone({
			    			url:base+"/file/upload.do",
			    	        maxFiles: opts.maxFiles,//最大文件个数
			    	        maxFilesize: opts.max_file_size,//最大文件大小MB
			    	        uploadMultiple : opts.uploadMultiple, //文件是否可以多选
			    	        acceptedFiles: opts.filters,//可以上传的文件
			    	        paramName: "file",//后台文件类型接受的参数名称
			    	        params: params,//后台可接受的参数
			    	        addRemoveLinks : false,
			    			dictDefaultMessage :'<span class="bigger-150 bolder"><i class="ace-icon fa fa-caret-right red"></i>点击或拖拽文件</span>  \
								<span class="smaller-80 grey"></span> <br /> \
								<i class="upload-icon ace-icon fa fa-cloud-upload blue fa-3x"></i>',
			    							
			    		  dictResponseError: '文件上传发生错误',
			    	      dictFallbackMessage: "浏览器不支持拖拽文件上传",
			    	      dictFileTooBig: "文件过大 ({{filesize}}MB). 最大: {{maxFilesize}}MB.",
			    	      dictInvalidFileType: "无法上传此类型的文件.",
			    	      dictResponseError: "服务器响应码： {{statusCode}}",
			    	      dictCancelUpload: "取消上传",
			    	      dictCancelUploadConfirmation: "是否确定取消此文件上传?",
			    	      dictRemoveFile: "移除文件",
			    	      dictRemoveFileConfirmation:"是否确定移除此文件",
			    	      dictMaxFilesExceeded: "无法上传文件",
			    	      //初始化监听事件（非重写默认方法）
			    	      init: function() {
			    	      		//新增文件
			    		        this.on("addedfile",function(file){
			    		        	
			    		        	//debugger;
			    		            var removeButton = Dropzone.createElement("<a class=\"dz-remove\" href=\"javascript:undefined;\" data-dz-remove=\"\">移除文件</a>");


			    		            var _this = this;

			    		            //监听单击事件
			    		            removeButton.addEventListener("click", function(e) {
			    		              //阻止冒泡
			    		              e.preventDefault();
			    		              e.stopPropagation();
			    		             // debugger;
			    		              $.post(base+"/file/deleteFile.do",{"belongOrg":opts.orgId,"fileName":file.md5Name,"fileId":file.fileId,"attachId":file.attachId,"fileType":1},function(result){
			    		            	  if(result[0] == "ok"){
			    		            		  _this.removeFile(file);
			    		            	  }else{
			    		            		  alert("删除文件失败！");
			    		            	  }
			    		              });
			    		              
			    		            });
			    		            
			    		           // var tmp = file.previewElement.getElementsByClassName("dz-remove")[0];
			    		            //file.previewElement.removeChild(tmp);
			    		            file.previewElement.appendChild(removeButton);
			    		        });
			    		        //文件上传成功
			    		        this.on("success", opts.uploadSuccess);
			    		        
			    		        //删除文件
			    		        this.on("removedfile", opts.removedFile);
			    		        //文件上传成功或失败都会执行的方法
			    		        this.on("complete",function(file){
			    		        	var response = JSON.parse(file.xhr.response);
			    		        	file.md5Name = response.md5Name;
			   			    	 	file.fileId = response.fileId;
			   			    	    file.filePath = response.filePath;
			   			    	    file.attachId = response.attachId;
			    		        });
			    		    }
			    	        
			    	    });
			    		//文件上传插件 end
		    		});
		    		//打开文件上传之前判断
		    		 if(undefined!=opts.checkBefore){
						 if(!checkBefore()){
							 return;
						 }
					 }
					$("#fileUploadPage").dialog("open");
					
		    	});
			});
		 };
		 
		 
		 $.fn.hiwanFileUpload.defaults = {
				  url:'',//自定义url 如果为空则用默认的url处理
				  busiId:'', //作为文件的挂靠业务id 必输
				  orgId:'', //作为区分文件的维度，非必输
				  type:'file',//file or image 默认为作为file处理
				  max_file_size:10,
				  filters:null,
				  uploadMultiple : true,
				  maxFiles : 10,
				  debug: false,//是否开启debug
				  uploadSuccess:function(file,status){alert("所有文件上传成功");},//所有文件上传成功 
				  fileAdded: function(file){},//文件添加 
				  removedFile:function(file){},//文件删除
				  error:function(file,error,request){}//出错
		 };
	
})(jQuery);   

function _init(obj, opts){
  	if (opts.debug == true) {
		//debugger;
	}
  	
    $("#common_select_org_container").remove();
	$("BODY").append('<div id="common_select_org_container"></div>');
	var defaultOrgId = opts.defaultOrgId;
	var showOrgId = obj.attr("id") + "Show";
	var defaultOrgName = opts.defaultOrgName; 
	if(defaultOrgId != "") {
		obj.val(defaultOrgId);
	}
	if($("#"+showOrgId)){
		$("#"+showOrgId).remove();
	}

	//获得obj的标签名、属性、样式并克隆一个一模一样的标签，id加个Show后缀
 	var id = obj.attr("id");
 	obj.wrap("<div></div");
 	var objhtml = obj.parent().html();
 	obj.attr("id", showOrgId);
 	//obj.after("<input id='" + showOrgId + "' style='float:left' type='text' value='"+defaultOrgName+"'/>");
 	obj.after(objhtml);
 	var newobj = $("#"+id);
 	newobj.attr("id", showOrgId);
 	obj.attr("id", id);
 	newobj.attr("value", defaultOrgName);
 	newobj.attr("name","");
 	newobj.attr("readonly", true);
 	newobj.show();
 	obj.hide();
 	
	if (opts.readonly == false) {
	var resetOrgId = obj.attr("id") + "Reset";
	if($("#"+resetOrgId)){
 		$("#"+resetOrgId).remove();
 	}
	newobj.css("float","left");
 	$("#" + showOrgId).after('<a id="' + resetOrgId + '" class="ui-icon ui-icon-close" style="float:left;margin-left:.5em;" href="#"></a>');
 	if (opts.reset != '1') {
 		$("#" + resetOrgId).hide();
 	}
  	$("#" + showOrgId).click(function() {
 		if (!opts.beforeSelect()) {
 			return;
 		}
 		if(!opts.isCheckBox) {
        		$("#common_select_org_container").dialog({hide:true,autoOpen: false,width: 400,height:480, modal: true,bgiframe: true,resizable: false,position: {
    				my: "center",
    				at: "center",
    				of: window,
    				within: $("body")
    				},
        			close: function(event, ui) {
        				if($("#returnData").val() != "") {
        					var arr=eval("("+$("#returnData").val()+")");
        					if(arr != null) {
	        					obj.val(arr.orgId);
	        					$("#" + showOrgId).val(arr.orgName);
        					}
        					if(opts.afterSelect != undefined || opts.afterSelect !=null)
        						opts.afterSelect();
        				}
            			$("#common_select_org_container").dialog("destroy");
            			$("#common_select_org_container").empty();
        			}			
        		});
 		} else {
 			$("#common_select_org_container").dialog({hide:true,autoOpen: false,width: 400,height:480, modal: true,bgiframe: true,resizable: false,position: {
    				my: "center",
    				at: "center",
    				of: window,
    				within: $("body")
    				},
    				buttons: {
						"确认": function() {
							var checkedNodes = zTreeSelect.getCheckedNodes(true);
							$("#returnData").data("treeNode", checkedNodes);
							$("#common_select_org_container").dialog("close");
						},
						"关闭": function() {
							$("#common_select_org_container").dialog("close");
							$("#common_select_org_container").empty();
						}
					},
        			close: function(event, ui) {
        				var checkedNodes = $("#returnData").data("treeNode");
        				var orgIds = "",orgNames = "";
						if(checkedNodes) {
							for(var i = 0; i < checkedNodes.length;i++) {
								orgIds = orgIds + checkedNodes[i].id + ",";
								orgNames = orgNames + checkedNodes[i].name + ",";
							}
							obj.val(orgIds.substr(0,orgIds.length - 1));
							$("#" + showOrgId).val(orgNames.substr(0,orgNames.length - 1));
							if(opts.afterSelect != undefined || opts.afterSelect !=null)
        						opts.afterSelect();
						}
            			$("#common_select_org_container").dialog("destroy");
            			$("#common_select_org_container").empty();
        			}
 			});
 		}
 		var params;
 		var url = base + "/org/";
 		if(opts.forReport == true){
 			url = url + "haveOrgTreeForReport.action"; 
 			params={
 					"id":opts.queryRootOrgId.replace(/(^\s*)|(\s*$)/g, ""),
 					"checkType":opts.checkType,
 					"isRoot":"true",
 					"forReport":opts.forReport,
 					"isCheckBox":opts.isCheckBox,
 					"isNotCheckMessageType":opts.isNotCheckMessageType};
 		}else{
 			url = url + "orgSelectTree";
 			params={"checkType":opts.checkType,
 					"messageType":opts.messageType,
 					"noSuper":opts.noSuper,
 					"forReport":opts.forReport,
 					"isCheckBox":opts.isCheckBox,
 					"clickType":opts.clickType,
 					"isNotCheckMessageType":opts.isNotCheckMessageType,
 					"mapperId":opts.mapper.mapperId,
 					"paramsJson":opts.mapper.paramsJson,
 					"id":opts.queryRootOrgId.replace(/(^\s*)|(\s*$)/g, "")};
 		}
 		
 		var jsonParam=JSON.stringify(params);
     	$("#common_select_org_container").load(url,{"params":jsonParam});
     	$("#common_select_org_container").dialog("open"); 
 	});
  	
  	$("#" + resetOrgId).click(function() {
  		obj.val("");
 	  	$("#" + showOrgId).val("");
 	}); 
  	
  	
	}	
}

function getOs() 
{ 
   if(navigator.userAgent.indexOf("MSIE")>0) { 
        return "MSIE"; 
   } 
   if(navigator.userAgent.indexOf("Firefox")>0){ 
        return "Firefox"; 
   } 
   if(navigator.userAgent.indexOf("Safari")>0) { 
        return "Safari"; 
   }  
   if(navigator.userAgent.indexOf("Camino")>0){ 
        return "Camino"; 
   } 
   if(navigator.userAgent.indexOf("Gecko/")>0){ 
        return "Gecko"; 
   } 
   
}


/**
 * 将form serialize格式的字符串转化为json对象
 */
function formStrToJson(str){
    var str = decodeURIComponent(str,true);
    str = str.replace(/&/g,"','");    
    str = str.replace(/=/g,"':'");    
    str = "({'"+str +"'})";
    obj = eval(str);
    return obj;   
}

